<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Welcome extends CI_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -  
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in 
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see http://codeigniter.com/user_guide/general/urls.html
	 */

	public function __construct()
	{
		parent::__construct(); 

		$this->load->model('store_model');    
		$this->load->model('item_model');
		$this->load->model('gen_bill_model');
		$this->load->model('user_model');
		$this->load->helper('url');
		$this->load->helper('form');
	}

	public function get_user_id()
	{
		$user_id = $this->input->get('userid', TRUE);
		
		if ($user_id == "")
		{
			// Get history user info by session
			$user_id = $this->session->userdata('user_id');
			
			if ($user_id == False)
			{
				$this->load->view('tips/loginfail');
			}
		}

		return $user_id;	
	}

	public function index()
	{
		$user_id = $this->get_user_id();
		// login to session
		$this->session->set_userdata('user_id', $user_id);	
		$tab = $this->input->get('tab',true);
		if ($tab=='waimai')
		{
			redirect(site_url("welcome/shop")); // 隐藏在链接中显示的userid
		}
		else if ($tab=='tuangou')
		{
			redirect(site_url("grouppurchase")); // 隐藏在链接中显示的userid
		}
		else if ($tab=='geren')
		{
			redirect(site_url("welcome/info")); // 隐藏在链接中显示的userid
		}
		else//直接进入主页
		{
			redirect(site_url("welcome/in")); // 隐藏在链接中显示的userid
		}
	}

	public function in()
	{
		$user_id = $this->get_user_id();

		// login to session
		$this->session->set_userdata('user_id', $user_id);	

		$data['user_id'] = $user_id;
		$data['user_info'] = $this->get_user_info($user_id);

		$this->load->view('index/welcome_message', $data);
	}

	public function get_user_info($user_id)
	{
		$query = $this->user_model->get_user($user_id);
		if ($query == null)
		{
		    $data = array(
		      'user_id' => $user_id,
		      'user_name'  => '',
		      'phone'  => '',
		      'address'  => '',
		      'user_mail'  => '',
		    );
			return $data;
		}
		else return $query;
	}

	public function shop()
	{
		$data['user_id'] = $this->get_user_id();
		$data['store_list'] = $this->store_model->get_show_stores();
		$this->load->view('index/shop', $data);
	}

	public function store()
	{
		$data['user_id'] = $this->get_user_id();
		$store_id = $this->input->get("store_id", TRUE);
		$data['store_id'] = $store_id;
		if ($store_id == "")
		{
			// $data['reason'] = '请不要胡乱操作，小心导致不良后果！';
			// $data['reason2'] = '我知道错了，我要正确操作';
			$this->load->view('tip/failed',$data);
			return;
		}
		$shop_hours = $this->store_model->get_shop_hours($store_id);
		$time = time();
		$store_open_time = strtotime($shop_hours['store_open_time']);
		$store_close_time = strtotime($shop_hours['store_close_time']); 
		if (($store_open_time<$store_close_time and $time>$store_open_time and $time<$store_close_time)
			or ($store_open_time>$store_close_time and ($time>$store_open_time or $time<$store_close_time)))
		{
			$data["store_info"]= $this->store_model->get_store($store_id);
			$data["item_list"] = $this->item_model->get_items($store_id);
			$data["store_bottom_price"] = $this->store_model->get_store_bottom_price($store_id);
			$this->load->view('index/store', $data);
		}
		else
		{
			redirect(site_url('welcome/index'));
		}
	}

	 public function newbill()
	 {
	    $data['title'] = '下单成功';
	    $user_id = $this->get_user_id();
	    $billjson = $this->input->post("billjson");
	    if ($billjson == "")
	    	redirect('/?userid=' . $user_id);
	    $data['user_id'] = $user_id;


        $detail = json_decode($billjson, true);
	    $store_id = $detail['store_id'];
		$store_info = $this->store_model->get_store($store_id);

		$time = time();
		$store_open_time = strtotime($store_info[0]['store_open_time']);
		$store_close_time = strtotime($store_info[0]['store_close_time']); 
		$store_state = $store_info[0]['store_state'];
		if ((string)$store_state != '1')//打烊或者隐藏
		{
			$data['reason'] = '店铺已经打烊或忙碌，请选择其他店铺进行下单！';
			$data['reason2'] = '选择其他店铺进行下单';
			$this->load->view("tips/failed",$data);
			return;
		}
		
		if (!($store_open_time<$store_close_time and $time>$store_open_time and $time<$store_close_time) 
            and !($store_open_time>$store_close_time and ($time>$store_open_time or $time<$store_close_time)))
		{
			$data['reason'] = '店铺已经打烊，请选择其他店铺进行下单！';
			$data['reason2'] = '选择其他店铺进行下单';
			$this->load->view("tips/failed",$data);
			return;
		}

	    $result = $this->gen_bill_model->new_bill($user_id);
	    if( $result == 2)//下单成功
	    {
	      $this->load->view('tips/success', $data);

	      $bill_id = $this->db->insert_id();
          $detail = json_decode($billjson, true);
		  $name = $this->input->post("fname");
		  $phone = $this->input->post("phone");
		  $address = $this->input->post("address");
		  $note = $this->input->post("note");
    	$dorm = $this->input->post("dorm");
    	if ($dorm == null or $dorm == 0)
    		$dorm = "未填写";
    	else
    		$dorm = "宿舍 " . $dorm . " 号楼";

		  $content = "订购姓名：" . $name 
		  			."\n订单编号：" . $bill_id
		  			."\n联系电话：" . $phone
		  			."\n送货地址：" . $address
		  			."\n送货楼栋：" . $dorm
		  			."\n外卖备注：" . $note
		  			."\n下单时间：" . date('Y-m-d H:i:s', time())
		  			."\n外卖店铺：" . $detail["store_name"]
		  			."\n外卖总价：" . $detail["total_price"]
		  			."\n\n订单详情：";

		  foreach ($detail['list'] as $item):
		  	if ($item['item_account'] > 0)
		  		$content .= "\n" . $item['item_name'] . "\t\t" . $item['item_price'] . "\t\t" . $item['item_account'];
		  endforeach;

		  $store_mail = $this->store_model->get_store_mail($detail["store_id"]);
		  $this->send2mail($store_mail, "新订单 ".$bill_id, $content);
	    }
	    else if( $result == 0)//由于信息不全导致的下单失败
	    {
	    	$data['reason'] = '请检查您是否准确完整填写姓名、联系方式以及收货地址';
	    	$data['reason2'] = '完善信息';
	      	$this->load->view('tips/failed', $data);
	    }
	    else//重复下单导致的下单失败
	    {
	      $this->load->view('tips/duplicate_bill', $data);
	    }
	 }

	  public function send2mail($mail, $title = "新订单", $content = "")
	  {
	    $config['protocol'] = 'smtp';
		$config['charset'] = 'utf-8';
		$config['wordwrap'] = TRUE;
		$config['smtp_host'] = 'smtp.163.com';
		$config['smtp_user'] = 'juhuijiainfo@163.com';
		$config['smtp_pass'] = 'juhuijiainfo123';

		$this->load->library('email');

		$this->email->initialize($config);


		$this->email->from('juhuijiainfo@163.com', '刘晓宁');
		$this->email->to(/*'769904450@qq.com,'*/'juhuijiainfo@163.com,' . $mail); 
	
		$this->email->subject($title);
		$this->email->message($content); 

		$this->email->send();

		//echo $this->email->print_debugger();
	  }


	public function success()
	{
		$this->load->view('tip/success', $data);
	}

	public function history()
	{
		$user_id = $this->get_user_id();
	    $total_rows = $this->gen_bill_model->get_history_bill_num($user_id);
	    $total_rows = $total_rows['count'];


		$per_page = 8;
		$data['total_rows'] = $total_rows;
		$data['user_id'] = $user_id;
		$data['per_page'] = $per_page;
	                
	    //load the model and get results
		$now_page = $this->input->get("page_num" , true);
		if ($now_page == "") 
			$now_page = 1;
	    $data['history_bill'] = $this->gen_bill_model->get_history_bill($user_id, $per_page, ($now_page-1)*$per_page);
	                
	    // load the HTML Table Class
	    $this->load->library('table');
	                
	    // load the view
	    $this->load->view('history/history', $data);
	}

	public function historyBill()
	{
		$bill_id = $this->input->get("billid", true);
		$query = $this->gen_bill_model->get_bill($bill_id);
		$data['query'] = $query;
		$this->load->view("history/history_bill", $data);
	}

	public function info()
	{
		if ($_POST)
		{
		    $user_id = $this->get_user_id();
			$data['user_id'] = $user_id;
			$flag = true;
		    $name = $this->input->post('name');
		    $phone = $this->input->post('phone');
		    $address = $this->input->post('address');
		    $dorm = $this->input->post('dorm');
		    $email = $this->input->post('email');
			$data['name'] = $name;
			if ($name == '')
			{
				$data['name_alert'] = '姓名不能为空,请重新检查!';
				$flag = false;
			}
			else $data['name_alert'] = '';
			$data['address'] = $address;
			if ($address == '')
			{
				$data['address_alert'] = '地址不能为空,请重新检查!';
				$flag = false;
			}
			else $data['address_alert'] = '';
			$data['dorm'] = $dorm;
			if ($dorm == '')
			{
				$data['dorm_alert'] = '楼栋号不能为空,请重新检查!';
				$flag = false;
			}
			else $data['dorm_alert'] = '';
			$data['phone'] = $phone;
			//手机号码的正则验证   
			if(preg_match("/^0?1[3|4|5|8][0-9]\d{8}$/",$phone)){   
				$data['phone_alert'] = '';
			}else{   
				$data['phone_alert'] = '手机号错误，请重新检查!';
				$flag = false;
			}  
			$data['email'] = $email;
			$data['email_alert'] = '';
			//邮箱的正则验证
			if ($email != '')
			{
				if(preg_match("/^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/",$email)){   
					$data['email_alert'] = '';
				}else{   
					$data['email_alert'] = '邮箱错误，请重新检查!';
					$flag = false;
				}
			}

			if ($flag)
		    	$query = $this->user_model->update_user($user_id);
			$this->load->view("index/personal_info",$data);
			return;
		}
		$user_id = $this->get_user_id();
		$query = $this->user_model->get_user($user_id);
		if ($query == null)
		{
			$data['user_id'] = $user_id;
			$data['name'] = '';
			$data['name_alert'] = '';
			$data['address'] = '';
			$data['address_alert'] = '';
			$data['dorm'] = '';
			$data['dorm_alert'] = '';
			$data['phone'] = '';
			$data['phone_alert'] = '';
			$data['email'] = '';
			$data['email_alert'] = '';
		}
		else
		{
			$data['user_id'] = $user_id;
			$data['name'] = $query['user_name'];
			$data['address'] = $query['address'];
			$data['dorm'] = $query['dorm'];
			$data['phone'] = $query['phone'];
			$data['email'] = $query['user_mail'];
			$data['name_alert'] = '';
			$data['address_alert'] = '';
			$data['dorm_alert'] = '';
			$data['phone_alert'] = '';
			$data['email_alert'] = '';
		}
		$this->load->view("index/personal_info",$data);
	}
	
	public function generalPay()
	{
		$user_id = $this->get_user_id();
		$data['user_id'] = $user_id;
		$data['user_info'] = $this->get_user_info($user_id);
		$data['dorm'] = $data['user_info']['dorm'];
		$this->load->view("index/general_pay", $data);
	}
}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */
